package com.foreveross.project.usercenterserver.oauth2.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foreveross.project.usercenterserver.common.constant.GlobalConstant;
import com.foreveross.project.usercenterserver.common.constant.ResultCode;
import com.foreveross.project.usercenterserver.common.utils.CodeUtils;
import com.foreveross.project.usercenterserver.common.utils.ContextUtil;
import com.foreveross.project.usercenterserver.exception.CustomException;
import com.foreveross.project.usercenterserver.oauth2.domain.UcApp;
import com.foreveross.project.usercenterserver.oauth2.domain.UcTenant;
import com.foreveross.project.usercenterserver.oauth2.dto.AppDto;
import com.foreveross.project.usercenterserver.oauth2.enums.DelFlagEnum;
import com.foreveross.project.usercenterserver.oauth2.mapper.UcAppMapper;
import com.foreveross.project.usercenterserver.oauth2.mapper.UcTenantMapper;
import com.foreveross.project.usercenterserver.oauth2.service.IUcAppService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * app服务实现类
 * </p>
 *
 * @author yz
 * @since 2019-07-19
 */
@Service
public class UcAppServiceImpl extends ServiceImpl<UcAppMapper, UcApp> implements IUcAppService {

    @Autowired
    private UcTenantMapper ucTenantMapper;

    @Override
    public UcApp createApp(AppDto appDto) {
        //验证参数
        this.validityData(appDto);
        UcApp app = new UcApp();
        BeanUtil.copyProperties(appDto, app);
        app.setCreateBy(ContextUtil.getCurrentUserId());
        app.setCreateAt(new Date());
        app.setDelFlag(DelFlagEnum.NORMAL.getDelFlag());
        app.setAppFkId(CodeUtils.getUUID());
        int insert = baseMapper.insert(app);
        app.setId(insert);
        return app;
    }

    @Override
    public UcApp updateApp(AppDto appDto) {
        this.validityData(appDto);
        //修改则检查app是否存在
        UcApp ucApp = null;
        if (StrUtil.isEmpty(appDto.getAppFkId())) {
            throw new CustomException(GlobalConstant.ERROR_APP_NOT_EXISTENT_MSG);
        }
        ucApp = this.findApp(appDto.getAppFkId());
        if (ObjectUtil.isNull(ucApp)) {
            throw new CustomException(GlobalConstant.ERROR_APP_NOT_EXISTENT_MSG);
        }
        BeanUtil.copyProperties(appDto, ucApp);
        ucApp.setUpdateAt(new Date());
        ucApp.setUpdateBy(ContextUtil.getCurrentUserId());
        baseMapper.updateById(ucApp);

        return ucApp;
    }

    @Override
    public UcApp deleteApp(String appFkId) {
        //TODO 是否需要检查操作权限？当前操作人是否该记录的创建者？
        //TODO 删除租户的时候设置租户下的各种资源不可用？？？
        UcApp ucApp = null;
        ucApp = this.findApp(appFkId);
        if (ObjectUtil.isNull(ucApp)) {
            throw new CustomException(GlobalConstant.ERROR_APP_NOT_EXISTENT_MSG);
        }
        if (ucApp.getDelFlag() < 0) {
            throw new CustomException(GlobalConstant.ERROR_APP_NOT_EXISTENT_MSG);
        }
        ucApp.setDelFlag(DelFlagEnum.ISDEL.getDelFlag());
        ucApp.setUpdateAt(new Date());
        ucApp.setUpdateBy(ContextUtil.getCurrentUserId());
        baseMapper.updateById(ucApp);
        return ucApp;
    }

    @Override
    public IPage<UcApp> queryForPage(Page<UcApp> page, Map<String, Object> params) {
        return baseMapper.queryForPage(page, params);
    }


    @Override
    public UcApp findApp(String appFkId) {
        UcApp ucApp = null;
        QueryWrapper<UcApp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_fk_id", appFkId);
        ucApp = baseMapper.selectOne(queryWrapper);
        return ucApp;
    }

    private void validityData(AppDto appDto) {
        if (StrUtil.isEmpty(appDto.getTenantFkId()) || StrUtil.isEmpty(appDto.getAppName()) || StrUtil.isEmpty(appDto.getAppCode())) {
            throw new CustomException(GlobalConstant.ERROR_MESSAGE_PARAMETER_ABSENCE, ResultCode.BAD_REQUEST.getCode());
        }
        QueryWrapper<UcTenant> wrapper = new QueryWrapper<>();
        wrapper.eq("tenant_fk_id", appDto.getTenantFkId());
        UcTenant tenant = ucTenantMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(tenant)) {
            throw new CustomException(GlobalConstant.ERROR_TENANT_NON_EXISTENT_MSG);
        }
        if (tenant.getDelFlag() < 0) {//已被删除的租户
            throw new CustomException(GlobalConstant.ERROR_TENANT_NON_EXISTENT_MSG);
        }
        QueryWrapper<UcApp> appQueryWrapper = new QueryWrapper<>();
        appQueryWrapper.eq("app_code", appDto.getAppCode());
        appQueryWrapper.eq("tenant_fk_id", appDto.getTenantFkId());
        //不同租户，应用code可以相同
        //检查是否存在相同的app名称
        UcApp app = baseMapper.selectOne(appQueryWrapper);
        if (StrUtil.isNotEmpty(appDto.getAppFkId())) {
            //修改状态
            if (!app.getAppFkId().equalsIgnoreCase(appDto.getAppFkId())) {
                throw new CustomException(GlobalConstant.ERROR_APP_REPEAT_MSG);
            }
        } else {
            //新增状态
            if (ObjectUtil.isNotNull(app)) {
                throw new CustomException(GlobalConstant.ERROR_APP_REPEAT_MSG);
            }
        }
    }
}
